#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>

void initMem();
int getMem();
void freeMem(int position);
void displayMap();
int power(int base, int n);

int bmap[8] = {0,56,856,96576,1,1234,0,0};
int tryand = 0x80000000;

int main(){
    int zero=0;
    int i =0;
    int p; 
    displayMap();
    initMem();
   /* p = getMem();
    printf("%d",p); */
    freeMem(45);
    
}

    void initMem(){
        int i =0;
        for(i=0; i<8; i++){
            bmap[i] = 0;
            printf("%0.8x\n", bmap[i]);
        }
    }
    
    
    int getMem(){
        int p=0;
        int i = 0;
        int j = 0;
        int temp;
        int trythis = 0x80000000;

        for(i=0;i<8;i++){
            temp = bmap[i];
            /* printf("reading line: %0.8x\n", temp); */

            for(j=0;j<32;j++){
                printf("trying line: %0.8x\n", temp);
                if((temp & tryand) == trythis){
                    printf("line found: %0.8x\n", temp);
                    return p;
                }
                else{

                    temp <<= 1;
                    p++;
                }
            }
            if(p > 256){
                return -1;
            }
        }
        return EXIT_SUCCESS;
    }


    void freeMem(int position){
        int i=0;
        int p=0;
        int m=0;
        int temp;

        if((position < 0) || (position > 255)){
            printf("value %d is out of range");
        }
        else if (position == 0) {
            bmap[0] <<= 1;
            bmap[0] >>= 1;
        }
        else{
            p=(position/32);
            m=(position%32);
            m--;
            temp = power(2,m);
            printf("looking in row %d for item number %d",p,m);
            printf("\nXORing with %0.8x",temp);
            bmap[p] = (bmap[p] | 0xffffffff);
            temp = temp ^ bmap[p];
            printf("\nnew line %d is %0.8x",p,temp);
        }
    }

    void displayMap(){
        int i=0;
        for (i=0;i<8;i++) {
            printf("\n%0.8x",bmap[i]);
        }
    }
    
    int power (int base, int n) {
        int i;
        int p;

        p = 1;

        for (i = 1; i <= n; i++) {
            p = p * base;
        }

        return p;
    }

